<script setup>
import { ref, onMounted, inject, onUnmounted, nextTick } from 'vue'

import { getPostgraduateAnalysisService } from '@/api/dataAnalysis';
import { getGraduateYears, getGraduateColleges, getGraduateMajors } from '@/api/graduate';
const echarts = inject('echarts')
// DOM 引用和图表实例
const chartContainer = ref(null)
const chartInstance = ref(null)
const allData = ref([])
const startValue = ref(0)
const endValue = ref(7)
const timerId = ref(null)
const totalFurtherStudy = ref(0)


const getPostgraduateAnalysisData = async (params) => {
  try {
    const res = await getPostgraduateAnalysisService(params)
    console.log('数据获取成功:', res.data);
    totalFurtherStudy.value = res.data.reduce((total, item) => total + item.value, 0)
    allData.value = res.data.sort((a, b) => b.value - a.value)
    updateChart()
    startInterval()
  } catch (error) {
    console.error('数据获取失败:', error)
  }
}



// 颜色渐变函数
const getColorGradient = (arg) => {
  const colorArr = [
    ['#0BA82C', '#4FF778'],
    ['#2E72BF', '#23E5E5'],
    ['#5052EE', '#AB6EE5']
  ]

  let targetColorArr = null
  if (arg.value > 10) {
    targetColorArr = colorArr[0]
  } else if (arg.value > 5) {
    targetColorArr = colorArr[1]
  } else {
    targetColorArr = colorArr[2]
  }
  return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
    { offset: 0, color: targetColorArr[0] },
    { offset: 1, color: targetColorArr[1] }
  ])
}

const option = {
    title: {
      text: '▎ 高校深造人数排行',
      left: 20,
      top: 20,
      textStyle: {
      color: '#333',
        fontSize: 20
      }
    },
    grid: {
      top: '25%',
      left: '5%',
      right: '10%',
      bottom: '5%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      name: '深造院校',
      axisLabel: {
        fontSize: 12,
        interval: 0,
        formatter: (value) => value.length > 4
          ? value.slice(0, 4) + '\n' + value.slice(4)
          : value
      },
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value',
      name: '单位/人',
      nameTextStyle: {
        padding: [0, 0, 0, 10]
      },
      minInterval: 1,
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [{
      type: 'bar',
      // barWidth: (allData.value.length <= 2) ? '30%' : '60%', // 根据数据量动态调整宽度
      // barCategoryGap: (allData.value.length <= 2) ? '50%' : '30%', // 调整柱间距
      itemStyle: {
        barBorderRadius: [30, 30, 0, 0]
      }
    }],
    dataZoom: {
      //取消显示缩放条
      show: false
    },
    tooltip: {
      show: true,
    }
  }
// 添加自适应方法
const screenAdapter = () => {
  if (!chartContainer.value || !chartInstance.value) return
  
  const titleFontSize = chartContainer.value.offsetWidth / 100 * 3.6
  const adapterOption = {
    title: {
      textStyle: {
        fontSize: titleFontSize
      }
    },
    series: [{
      barWidth: titleFontSize,
      itemStyle: {
        barBorderRadius: [titleFontSize / 2, titleFontSize / 2, 0, 0]
      }
    }]
  }
  chartInstance.value.setOption(adapterOption)
  chartInstance.value.resize()
}
// 初始化图表
const initChart = () => {
  if (!chartContainer.value) {
    return
  }

  chartInstance.value = echarts.init(chartContainer.value)
  const titleFontSize = chartContainer.value.offsetWidth / 100 * 3.6


  chartInstance.value.setOption(option)

  // 事件监听
  chartInstance.value.on('mouseover', () => clearInterval(timerId.value))
  chartInstance.value.on('mouseout', startInterval)
}

// 获取数据


// 更新图表
const updateChart = () => {
  if (!chartInstance.value) { return }

  const option = {
    xAxis: { data: allData.value.map(item => item.name) },
    series: [{
      data: allData.value.map(item => item.value),
      barWidth: allData.value.length <= 2 ? '30%' : '60%', // 动态宽度
      barCategoryGap: allData.value.length <= 2 ? '50%' : '30%', // 动态间距
      itemStyle: {
        color: (params) => getColorGradient(params)
      }
    }],
    dataZoom: {
      startValue: startValue.value,
      endValue: endValue.value,
      show: false
    }
  }

  chartInstance.value.setOption(option)
}

// 启动定时器
const startInterval = () => {
  clearInterval(timerId.value)
  timerId.value = setInterval(() => {
    startValue.value++
    endValue.value++
    if (endValue.value > allData.value.length - 1) {
      startValue.value = 0
      endValue.value = 7
    }
    updateChart()
  }, 2000)
}



onUnmounted(() => {
  // 添加移除事件监听
  window.removeEventListener('resize', screenAdapter)
  clearInterval(timerId.value)
  if (chartInstance.value) {
    chartInstance.value.dispose()
  }
})


// 响应式数据
const responseResult = ref(null)
const years = ref([])
const colleges = ref([])
const majors = ref([])
const selectedYear = ref('')
const selectedCollege = ref('')
const selectedMajor = ref('')

// 页面加载时获取年份数据
onMounted(async () => {
  const { data } = await getGraduateYears()
  years.value = data
  selectedYear.value = years.value[0]

  if (selectedYear.value) {
    const { data } = await getGraduateColleges(selectedYear.value)
    colleges.value = data
  } else {
    colleges.value = []
  }

  nextTick(async () => {
    initChart()
    await getPostgraduateAnalysisData({
      year: selectedYear.value
    })
    // 添加窗口resize监听
window.addEventListener('resize', screenAdapter)
  
  // 初始化时立即执行一次适配
  screenAdapter()
  })
})

// 年份变化时获取学院数据
const handleYearChange = async () => {
  selectedCollege.value = ''//空字符串时为假
  selectedMajor.value = ''
  majors.value = []
  console.log('年份变化', selectedYear.value);

  await getPostgraduateAnalysisData({
    year: selectedYear.value
  })

  if (selectedYear.value) {
    const { data } = await getGraduateColleges(selectedYear.value)
    colleges.value = data
  } else {
    colleges.value = []
  }
}

// 学院变化时获取专业数据
const handleCollegeChange = async () => {
  selectedMajor.value = ''

  console.log('学院变化', selectedCollege.value);
  if (selectedCollege.value) {
    await getPostgraduateAnalysisData({
      year: selectedYear.value,
      college: selectedCollege.value
    })
  }

  if (selectedYear.value && selectedCollege.value) {
    const { data } = await getGraduateMajors(selectedYear.value, selectedCollege.value)
    majors.value = data
  } else {
    majors.value = []
  }
}
const handleMajorChange = async () => {
  console.log('专业变化', selectedMajor.value);
  if (selectedMajor.value) {
    await getPostgraduateAnalysisData({
      year: selectedYear.value,
      college: selectedCollege.value,
      major: selectedMajor.value
    })
  }
}
// 添加重置方法
const handleReset = async () => {
  selectedYear.value = years.value[0]
  selectedCollege.value = ''
  selectedMajor.value = ''
  majors.value = []
  await getPostgraduateAnalysisData({
    year: selectedYear.value
  })
}
</script>

<template>

  <!-- 过滤筛选 -->
  <div class="filter-bar">
    <div class="filter-item">
      <span class="filter-label  word-1">毕业年份：</span>
      <el-select style="width: 150px" v-model="selectedYear" placeholder="请选择毕业年份" @change="handleYearChange">

        <el-option v-for="year in years" :key="year" :label="year" :value="year" />
      </el-select>
    </div>

    <div class="filter-item">
      <span class="filter-label word-1">学院：</span>
      <el-select v-model="selectedCollege" placeholder="请选择学院" :disabled="!selectedYear" @change="handleCollegeChange"
        style="width: 150px">
        <el-option v-for="college in colleges" :key="college" :label="college" :value="college" />
      </el-select>
    </div>

    <div class="filter-item">
      <span class="filter-label word-1">专业：</span>
      <el-select v-model="selectedMajor" placeholder="请选择专业" :disabled="!selectedCollege" @change="handleMajorChange"
        style="width: 150px">

        <el-option v-for="major in majors" :key="major" :label="major" :value="major" />
      </el-select>
    </div>
    <!-- 添加重置按钮 -->
    <el-button type="default" @click="handleReset">重置</el-button>
  </div>

  <div class="summary-text">
    总计深造人数共 <span class="highlight">{{ totalFurtherStudy }}</span> 人

  </div>

  <div class="graph_container" ref="chartContainer">
    柱状图显示
  </div>


</template>

<style lang="scss" scoped>
.filter-bar {
  display: flex;
  gap: 20px;
  // margin-bottom: 20px;
  padding: 15px;
  background: #fff;
  border-radius: 8px;

  .filter-item {
    display: flex;
    align-items: center;

    .filter-label {
      color: #61666d;
      margin-right: 8px;
    }
  }
}

.summary-text {
  padding: 15px;
  background: #fff;
  border-radius: 8px;
  // margin-bottom: 20px;

  .highlight {
    color: #00aeec;
    font-weight: 600;
    font-size: 18px;
  }
}

.graph_container {
  padding: 15px;
  max-width: 900px;
  background: #fff;
  border-radius: 8px;
  min-height: 600px;
  border: 2px dashed #00aeec;
  border-radius: 8px;
  // min-height: 175%;
}
</style>